package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.Userpharmacy;

@Repository(value = "userPharmacyDao")
@Transactional(readOnly = false)
public class UserPharmacyDaoImpl implements UserPharmacyDao {
	private EntityManager em = null;
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	} 
	
	@SuppressWarnings("unchecked")
	public List<Userpharmacy> getUserPharmacyList() {
		return em.createNamedQuery("Userpharmacy.findAll").getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Userpharmacy> getUserPharmacyList(boolean active) {
		Query q = em.createNamedQuery("Userpharmacy.findByActive");
    	q.setParameter("active",active);
    	return q.getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Userpharmacy> getUserPharmacyList(Integer userId) {
		Query q = em.createNamedQuery("Userpharmacy.findByUserId");
    	q.setParameter("userId",userId);
    	return q.getResultList();
	}
	
	public List<Userpharmacy> getListUserPharmacy(Integer pharmacyId,boolean active){
		TypedQuery<Userpharmacy> q = em.createNamedQuery("Userpharmacy.findByPharmacyIdByActive",Userpharmacy.class);
    	q.setParameter("pharmacyId",pharmacyId);
    	q.setParameter("active",active);
    	return q.getResultList();
	}

	
	public List<Userpharmacy> getListUserPharmacy(String login, String password){
		TypedQuery<Userpharmacy> q = em.createQuery("SELECT u FROM Userpharmacy u WHERE u.user.login = :login AND u.user.password = :password",Userpharmacy.class);
    	q.setParameter("login",login);
    	q.setParameter("password",password);
    	return q.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Userpharmacy> getUserPharmacyList(Integer userId, boolean active) {
		Query q = em.createNamedQuery("Userpharmacy.findByUserIdByActive");
    	q.setParameter("userId",userId);
    	q.setParameter("active",active);
    	return q.getResultList();
	}
	
	public Userpharmacy findByPharmacyIdByUserId(Integer pharmacyId,Integer userId) {			
		Userpharmacy res = null;
    	Query  q = em.createNamedQuery("Userpharmacy.findByUserIdByPharmacyId");
    	q.setParameter("pharmacyId",pharmacyId);
    	q.setParameter("userId",userId);
    	if(q.getResultList().size()==1)
    		res=(Userpharmacy)q.getSingleResult();
    	return res;
	}
    
    public void update(Userpharmacy userPharmacy) {
		em.merge(userPharmacy);
	}
	
	public void add(Userpharmacy userPharmacy) {
		em.persist(userPharmacy);
	}
}
